<?php
require_once(CORE_DIR.'Common.php');
require_once(CORE_DIR.'taskModel.php');
require_once(CORE_DIR.'userModel.php');
require_once(CORE_DIR.'mappers/YammerAuthMapper.php');


class yammerModel extends Model{

	function __construct(){
		$this->conn = $this->getConnection();
	}
	
	function addYammerData($userid, $oauth_token, $oauth_token_secret, $oauth_verifier=null){
		
		$query = "replace into yammerauth (userid, oauth_token, oauth_token_secret, oauth_verifier)
				  values (%d, '%s', '%s', '%s')";
		$query = $this->format($query, array($userid, $oauth_token, $oauth_token_secret, $oauth_verifier));
		return mysqli_query($this->conn, $query);
	}
		
	function setYammerAccessData($access_token, $access_token_secret, $oauth_verifier=null){
		
		$query = "update yammerauth set access_token=%s, access_token_secret=%s, oauth_verifier=%s";
		$query = $this->format($query, array($access_token, $access_token_secret, $oauth_verifier));
		return mysqli_query($this->conn, $query);
	}
	
	function deleteYammerData($userid){
		$query = "delete from yammerauth where userid=%d";
		$query = $this->format($query, array($userid));		
		return mysqli_query($this->conn, $query);		
	}	
		
	function getYammerData($userid){
		$query = "SELECT * FROM yammerauth WHERE userid=%d";
		$query = $this->format($query, array($userid));		
		$yammerResult = $this->execute($query, new YammerAuthMapper());
		$yammerDto = $yammerResult[0];
		if($yammerResult == null)
			$yammerDto = new YammerAuthDto();
		return $yammerDto;
	}		
	
	function isYammerActive($userid)
	{
		$yammerDto = $this->getYammerData($userid);
		if($yammerDto->getOAuthVerifier() != null && $yammerDto->getOAuthVerifier() != "null")
			return true;
		
		return false;
	}

	function oauth_headers($token = null, $token_secret = null, $verifier = null)
	{
		$header = "";
		
		$header .= "OAuth realm=\"";
		$header .= "\", oauth_consumer_key=\"";
		$header .= CONSUMER_KEY;
		$header .= "\", ";
	
		if ($token != null)
		{
			$header .= "oauth_token=\"";
			$header .= $token;
			$header .= "\", ";
		}
	
		$header .= "oauth_signature_method=\"";
		$header .= "PLAINTEXT";
		$header .= "\", oauth_signature=\"";
		$header .= CONSUMER_SECRET;
		$header .= "%26";
		if ($token_secret != null) {
			$header .= $token_secret;
		}
		$header .= "\", oauth_timestamp=\"";
		$header .= time();
		$header .= "\", oauth_nonce=\"";
		$header .= time();
	
		if ($verifier != null) {
			$header .= "\", ";
			$header .= "oauth_verifier=\"";
			$header .= $verifier;
		}
	
		$header .= "\", oauth_version=\"1.0\"";
	
		return $header;
	}
	
	function getRequestTokens()
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			"Content-Type: application/x-www-form-urlencoded",
			"User-Agent: DevNinja",
			"Authorization: " . $this->oauth_headers()
		));
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_URL, "https://www.yammer.com/oauth/request_token");
		curl_setopt($ch, CURLOPT_POST, true);
		$content = curl_exec($ch);
		
		$content = explode("&", $content);
		foreach ($content as $v) {
			$v = explode("=", $v);
			$$v[0] = $v[1];
		}

		$tokens = array();
		$tokens["oauth_token"] = isset($oauth_token) ? $oauth_token : false;
		$tokens["oauth_token_secret"] = isset($oauth_token_secret) ? $oauth_token_secret : false;
		return $tokens;
	}
	
	function getAccessTokens($reqToken, $reqTokenSecret, $verifier)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			"Content-Type: application/x-www-form-urlencoded",
			"User-Agent: DevNinja",
			"Authorization: " . $this->oauth_headers($reqToken, $reqTokenSecret, $verifier)
		));
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_URL, "https://www.yammer.com/oauth/access_token");
		curl_setopt($ch, CURLOPT_POST, true);
		$content = curl_exec($ch);

		$content = explode("&", $content);
		foreach ($content as $v) {
			$v = explode("=", $v);
			$$v[0] = $v[1];
		}

		$tokens = array();
		$tokens["oauth_token"] = isset($oauth_token) ? $oauth_token : false;
		$tokens["oauth_token_secret"] = isset($oauth_token_secret) ? $oauth_token_secret : false;
		return $tokens;
	}
	
	function sendMessageToYammer($reqToken, $reqTokenSecret, $verifier, $message)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			"Authorization: " . $this->oauth_headers($reqToken, $reqTokenSecret, $verifier)
		));
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_URL, "https://www.yammer.com/api/v1/messages");
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, array("body" => $message));
		$content = curl_exec($ch);
		
		return $content;
	}
	
	function sendDirectMessageToYammer($reqToken, $reqTokenSecret, $verifier, $message, $yammerId)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			"Authorization: " . $this->oauth_headers($reqToken, $reqTokenSecret, $verifier)
		));
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_URL, "https://www.yammer.com/api/v1/messages");
		curl_setopt($ch, CURLOPT_POST, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, array("body" => $message, 
												   "direct_to_id" => $yammerId));
		$content = curl_exec($ch);
		return $content;
	}

	function incYammerDirectMessage($user_id, $action_cmd, $params)
	{
		if (YAMMER_ACTIVE) {
			$uModel = new userModel();
			$userDto = $uModel->getActiveUser();
			if($user_id != $userDto->getId())
			{
				$body = file_get_contents(SITE_URL."?cmd=".$action_cmd."&".$params['querystr']);
				
				foreach($params as $key=>$value)
				{
					$body = str_replace($key, $value, $body);
				}
	
				if ( $this->isYammerActive($user_id))
				{
					$body = $this->removeSID($body);
					$body = strip_tags($body);
					$yammerDto = $this->getYammerData($user_id);
					$result = $this->sendDirectMessageToYammer($yammerDto->getOAuthToken(), 
					$yammerDto->getOAuthTokenSecret(), $yammerDto->getOAuthVerifier(), $body, $yammerDto->getYammerId());

					return $result;
				}
			}
		}
	}
	
	function removeSID($body)
	{
		$pos = strpos($body, "<sid>");
		$body = substr($body, 0, $pos);
		return $body;
	}
	
}
?>
